class AccountController < ApplicationController

  def login_by_wechat
    oid = params[:oid]

    user = User.where(wechat_openid: oid).first
    if user.present?
      user.remember_me!
      sign_in user
      redirect_to root_url, notice: '微信登陆成功'
    else
      render text: '该用户不存在'
    end
  end

  def bind
    oid = params[:oid]
    logger.info oid

    @user =  User.find_or_initialize_by(wechat_openid: oid)
  end

  def do_bind
    @user = User.new(user_params)

    user = User.find_by_email(@user.email)
    if user.try(:valid_password?, @user.password)
      openid = @user.wechat_openid

      wechat_config = YAML.load_file(File.join(Rails.root,'config/wechat.yml'))[Rails.env]
      corp_api = Wechat::CorpApi.new(*wechat_config.slice('appid', 'secret', 'access_token').values)
      user_info = corp_api.user(openid)
      user.update_attributes(wechat_openid: openid, wechat_nickname: user_info['name'])

      corp_api.message_send Wechat::Message.to(openid)
                                           .agent_id(Settings.wechat_agentid)
                                           .text('账户绑定成功')

      sign_in user
      redirect_to root_url, notice: '微信绑定成功'
    else
      # 邮箱或者密码错误
      flash.now.alert = '邮箱或密码错误'
      render :bind
    end
  end

  def unbind
    current_user.update(wechat_openid: nil, wechat_nickname: nil, wechat_unionid: nil)
    redirect_to edit_staff_path(current_user), notice: '微信解除绑定成功'
  end

  private
  def user_params
    params.require(:user).permit(:email, :password, :wechat_openid)
  end
end
